<template>
  <div class="system-logs">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="日志级别">
          <el-select v-model="searchForm.level" placeholder="请选择日志级别" clearable>
            <el-option label="DEBUG" value="DEBUG" />
            <el-option label="INFO" value="INFO" />
            <el-option label="WARN" value="WARN" />
            <el-option label="ERROR" value="ERROR" />
            <el-option label="FATAL" value="FATAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operationType" placeholder="请选择操作类型" clearable>
            <el-option label="登录" value="LOGIN" />
            <el-option label="新增" value="CREATE" />
            <el-option label="修改" value="UPDATE" />
            <el-option label="删除" value="DELETE" />
            <el-option label="查询" value="SELECT" />
            <el-option label="导出" value="EXPORT" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作用户">
          <el-input v-model="searchForm.username" placeholder="请输入操作用户" clearable />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="searchLogs">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          <el-button type="success" :icon="Download" @click="exportLogs">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-button type="danger" :icon="Delete" @click="batchDelete" :disabled="selectedLogs.length === 0">
        批量删除
      </el-button>
      <el-button type="warning" @click="handleClearOldLogs">
        <el-icon><DeleteFilled /></el-icon>
        清理旧日志
      </el-button>
    </el-card>

    <!-- 日志列表 -->
    <el-card>
      <el-table
        :data="logList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="日志ID" width="80" />
        <el-table-column prop="username" label="操作用户" width="120" />
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getOperationTypeTagType(row.operationType)">
              {{ getOperationTypeLabel(row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationDesc" label="操作描述" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="80" />
        <el-table-column prop="url" label="请求URL" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP地址" width="120" />
        <el-table-column prop="location" label="操作地点" width="150" />
        <el-table-column prop="level" label="日志级别" width="80">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时(ms)" width="100" />
        <el-table-column prop="createTime" label="操作时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="View" size="small" @click="viewLogDetail(row)">详情</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="deleteLog(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="700px"
      @close="closeDetailDialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="操作用户">{{ currentLog.username }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getOperationTypeTagType(currentLog.operationType)">
            {{ getOperationTypeLabel(currentLog.operationType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="日志级别">
          <el-tag :type="getLevelTagType(currentLog.level)">
            {{ currentLog.level }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求方法">{{ currentLog.method }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
        <el-descriptions-item label="操作地点">{{ currentLog.location }}</el-descriptions-item>
        <el-descriptions-item label="耗时(ms)">{{ currentLog.duration }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ currentLog.createTime }}</el-descriptions-item>
        <el-descriptions-item label="请求URL" :span="2">{{ currentLog.url }}</el-descriptions-item>
        <el-descriptions-item label="操作描述" :span="2">{{ currentLog.operationDesc }}</el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2">
          <pre>{{ formatJson(currentLog.requestParam) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="响应结果" :span="2">
          <pre>{{ formatJson(currentLog.responseResult) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="异常信息" :span="2" v-if="currentLog.exception">
          <pre style="color: #f56c6c;">{{ currentLog.exception }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete, Refresh, Download, View, DeleteFilled } from '@element-plus/icons-vue'
import { getSystemLogs, deleteSystemLogs, exportSystemLogs, clearOldLogs } from '@/api/system'

// 操作类型映射
const operationTypes = {
  'LOGIN': '登录',
  'CREATE': '新增',
  'UPDATE': '修改',
  'DELETE': '删除',
  'SELECT': '查询',
  'EXPORT': '导出'
}

// 搜索表单
const searchForm = ref({
  level: '',
  operationType: '',
  username: '',
  dateRange: []
})

// 日志列表数据
const logList = ref([])
const loading = ref(false)
const selectedLogs = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const currentLog = ref({})

// 加载日志列表
const loadLogList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm.value
    }
    
    // 处理日期范围
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      params.startDate = searchForm.value.dateRange[0]
      params.endDate = searchForm.value.dateRange[1]
    }
    
    const res = await getSystemLogs(params)
    logList.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('获取日志列表失败')
    console.error('Failed to load system logs:', error)
  } finally {
    loading.value = false
  }
}

// 搜索日志
const searchLogs = () => {
  currentPage.value = 1
  loadLogList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    level: '',
    operationType: '',
    username: '',
    dateRange: []
  }
  currentPage.value = 1
  loadLogList()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedLogs.value = val
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadLogList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadLogList()
}

// 获取操作类型标签类型
const getOperationTypeTagType = (type) => {
  const typeMap = {
    'LOGIN': 'primary',
    'CREATE': 'success',
    'UPDATE': 'warning',
    'DELETE': 'danger',
    'SELECT': 'info',
    'EXPORT': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取操作类型标签文本
const getOperationTypeLabel = (type) => {
  return operationTypes[type] || type
}

// 获取日志级别标签类型
const getLevelTagType = (level) => {
  const levelMap = {
    'DEBUG': 'info',
    'INFO': 'success',
    'WARN': 'warning',
    'ERROR': 'danger',
    'FATAL': 'danger'
  }
  return levelMap[level] || 'info'
}

// 查看日志详情
const viewLogDetail = (row) => {
  currentLog.value = row
  detailDialogVisible.value = true
}

// 关闭详情对话框
const closeDetailDialog = () => {
  detailDialogVisible.value = false
  currentLog.value = {}
}

// 删除日志
const deleteLog = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteSystemLogs([row.id])
    ElMessage.success('删除日志成功')
    loadLogList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除日志失败')
    }
  }
}

// 批量删除日志
const batchDelete = async () => {
  if (selectedLogs.value.length === 0) {
    ElMessage.warning('请选择要删除的日志')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedLogs.value.length} 条日志吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedLogs.value.map(item => item.id)
    await deleteSystemLogs(ids)
    ElMessage.success('批量删除日志成功')
    loadLogList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除日志失败')
    }
  }
}

// 清理旧日志
const handleClearOldLogs = async () => {
  try {
    await ElMessageBox.prompt('请输入要清理多少天前的日志（例如：30）', '清理旧日志', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^[1-9]\d*$/,
      inputErrorMessage: '请输入正整数'
    })
    .then(async ({ value }) => {
      await clearOldLogs(parseInt(value))
      ElMessage.success(`已清理${value}天前的日志`)
      loadLogList()
    })
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清理日志失败')
    }
  }
}

// 导出日志
const exportLogs = async () => {
  try {
    const params = {
      ...searchForm.value
    }
    
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      params.startDate = searchForm.value.dateRange[0]
      params.endDate = searchForm.value.dateRange[1]
    }
    
    const response = await exportSystemLogs(params)
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `系统日志_${new Date().toISOString().split('T')[0]}.xlsx`
    a.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 格式化JSON
const formatJson = (jsonStr) => {
  if (!jsonStr) return ''
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

// 初始化加载
onMounted(() => {
  loadLogList()
})
</script>

<style scoped>
.system-logs {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
}
</style>